package com.javatian.controller;

import cn.hutool.core.io.FileUtil;
import com.javatian.common.Result;
import com.javatian.entity.NxSystemFileInfo;
import com.javatian.exception.CustomException;
import com.javatian.service.NxSystemFileInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/files")
public class NxSystemFileController {
    @Value("${const.basePath}")
    private String basePath;

    @Resource
    private NxSystemFileInfoService nxSystemFileInfoService;

    /**
     * 文件上传
     */

    @PostMapping("/upload")
    public Result upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //原始文件名
        String originName = file.getOriginalFilename();
        //文件名后面加个时间戳
        String fileName = FileUtil.mainName(originName)+System.currentTimeMillis()+"."+FileUtil.extName(originName);
        //写入服务器文件
        FileUtil.writeBytes(file.getBytes(),basePath+fileName);
        //信息入库，获取文件id返回给前端
        NxSystemFileInfo info = new NxSystemFileInfo();
        info.setFileName(fileName);
        info.setOriginName(originName);
        NxSystemFileInfo add = nxSystemFileInfoService.add(info);
        if (add != null){
            return Result.success(add);
        }
        return Result.error("4001","上传失败");
    }

    /**
     * 文件下载
     */
    @GetMapping("/download/{id}")
    public void download(@PathVariable String id, HttpServletResponse response) throws IOException {
        if (null == id||"null".equals(id)||"".equals(id.trim())){
            throw new CustomException("1001","您未上传文件");
        }
        NxSystemFileInfo nxSystemFileInfo = nxSystemFileInfoService.findById(Long.parseLong(id));
        if (null == nxSystemFileInfo){
            throw new CustomException("1001","未查询到该文件");
        }

        byte[] bytes = FileUtil.readBytes(basePath + nxSystemFileInfo.getFileName());
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(nxSystemFileInfo.getFileName(),"UTF-8"));
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outputStream.write(bytes);
        outputStream.close();

    }
}













































